package service.impl;

import dao.UserDao;
import entity.User;
import exception.UserExistException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import service.UserService;

import java.util.List;

/**
 * @author 石小俊
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class, noRollbackFor = ArithmeticException.class, timeout = 1)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    // 方法上如果没有设置事务,则默认使用类上配置的
    @Override
    public void register(String username, String password, String phone, String address) throws UserExistException {
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        User selectUser = userDao.selectByUsername(username);
        if (selectUser != null) {
            throw new UserExistException("该用户已经被注册!");
        }
        User user = new User(username, password, phone, address);
        userDao.insertUser(user);
//        int i = 1 / 0;
    }

    @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
    @Override
    public List<User> findAll() {
        return userDao.selectAll();
    }
}
